#include "textobject.h"
#include "../doker.h"

#include <QtCore/qdebug.h>


TextObject::TextObject(const QString &content, QObject *parent) :
    QObject(parent)
{
    setObjectName("_text");
    m_content = content;
    m_sourceLineNumber = 0;
    m_width = -1.0;
    m_height = -1.0;
    m_x = m_y = -1.0;
    m_alignment = Qt::AlignLeft | Qt::AlignTop;
    m_color = QColor(Qt::black);
    m_font.setPixelSize(toPixels(Doker::defaultTextHeight));
}

QString TextObject::alignment() const
{
    QString a;
    if (m_alignment & Qt::AlignLeft)
        a += "left";
    else if (m_alignment & Qt::AlignHCenter)
        a += "center";
    else if (m_alignment & Qt::AlignRight)
        a += "right";
    else if (m_alignment & Qt::AlignJustify)
        a += "justify";
    a += " & ";
    if (m_alignment & Qt::AlignTop)
        a += "top";
    else if (m_alignment & Qt::AlignVCenter)
        a += "middle";
    else if (m_alignment & Qt::AlignBottom)
        a += "bottom";
    return a;
}

QString TextObject::cmyk() const
{
    QString res;
    res.sprintf("#%02X%02X%02X%02X",
                m_color.cyan(), m_color.magenta(), m_color.yellow(), m_color.black());
    return res;
}

QString TextObject::rgb() const
{
    QString res;
    res.sprintf("#%02X%02X%02X",
                m_color.red(), m_color.green(), m_color.blue());
    return res;
}

void TextObject::setAlignment(const QString &align)
{
    QString a = align.toLower();
    m_alignment = 0;

    if (a.contains("center"))
        m_alignment |= Qt::AlignHCenter;
    else if (a.contains("right"))
        m_alignment |= Qt::AlignRight;
    else if (a.contains("justify"))
        m_alignment |= Qt::AlignJustify;
    else
        m_alignment |= Qt::AlignLeft;

    if (a.contains("middle"))
        m_alignment |= Qt::AlignVCenter;
    else if (a.contains("bottom"))
        m_alignment |= Qt::AlignBottom;
    else
        m_alignment |= Qt::AlignTop;
}

void TextObject::setCmyk(const QString &cmyk)
{
    QString c = cmyk.simplified().toLower();
    bool ok = false;
    if (c.startsWith('#'))
    {
        quint32 code = c.mid(1).toUInt(&ok, 16);
        if (ok)
            m_color.setCmyk((code >> 24) & 0xFF, (code >> 16) & 0xFF,
                            (code >> 8 ) & 0xFF,  code & 0xFF);
    }
    if (!ok)
    {
        // TODO: Add Warning
    }
}

void TextObject::setRgb(const QString &rgb)
{
    QString c = rgb.simplified().toLower();
    bool ok = false;
    if (c.startsWith('#'))
    {
        quint32 code = c.mid(1).toUInt(&ok, 16);
        if (ok)
            m_color.setRgb((code >> 16) & 0xFF, (code >> 8 ) & 0xFF,  code & 0xFF);
    }
    if (!ok)
    {
        // TODO: Add Warning
    }
}

void TextObject::setSize(qreal s)
{
    m_font.setPixelSize(toPixels(s));
}

qreal TextObject::size() const
{
    return toUnits(m_font.pixelSize());
}
